import axios from 'axios'
import router from '../router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../stores/auth'

const instance = axios.create({})

instance.interceptors.request.use(cfg => {
  const token = localStorage.getItem('token')
  if (token) cfg.headers['Authorization'] = `Bearer ${token}`
  return cfg
})

instance.interceptors.response.use(res => {
  const data = res.data
  if (data && typeof data.code !== 'undefined' && data.code !== 0) {
    return Promise.reject(new Error(data.message || 'Error'))
  }
  return res
}, err => {
  if (err?.response?.status === 401) {
    const store = useAuthStore()
    store.logout()
    router.replace('/login')
  }
  const msg = err?.response?.data?.message || err.message || 'Error'
  ElMessage.error(msg)
  return Promise.reject(err)
})

export default instance


